package com.example.ctrip.commons;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import static com.example.ctrip.commons.Commons.getWEBDRIVER;

public class CommWebTools {
    private final static Logger logger = LoggerFactory.getLogger(CommWebTools.class);

    private static WebDriver webDriver;
    private static String proxyIp = "";

    public static WebDriver getWebDriver(String _proxyIp) {
        if (webDriver != null) {
            try {
                webDriver.getCurrentUrl();
            } catch (Exception e) {
                webDriver = null;
            }
        }
        if (!proxyIp.equalsIgnoreCase(_proxyIp)) {
            if (webDriver != null) {
                try {
                    webDriver.quit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                webDriver = null;
            }
        }
        if (webDriver == null) {
            System.setProperty("webdriver.chrome.driver", getWEBDRIVER());
            proxyIp = _proxyIp;
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--proxy-server=http://" + _proxyIp);
            webDriver = new ChromeDriver(options);

            webDriver.get("https://www.chinaexpressair.com/yss/login/");
            ((JavascriptExecutor) webDriver).executeScript("Object.defineProperties(navigator,{ webdriver:{ get: () => false } })");
        }
        return webDriver;
    }

    public static boolean isJudgingElement(WebDriver webDriver, By by) {
        try {
            webDriver.findElement(by);
            return true;
        } catch (Exception e) {
            System.out.println("不存在此元素");
            return false;
        }
    }

    public static boolean isJudgingElements(WebDriver webDriver, By by) {
        try {
            int count = 0;
            while (!isJudgingElement(webDriver, by)) {
                if (count >= 20) {
                    return false;
                }
                count++;
                Thread.sleep(1000);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String commonGet(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {

            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();
            httpGet.setConfig(requestConfig);

            httpGet.addHeader("Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            httpGet.addHeader("Accept-Encoding", "gzip, deflate");
            httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpGet.addHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36");
            httpGet.addHeader("Connection", "keep-alive");
            httpGet.addHeader("Host", "webapi.http.zhimacangku.com");

            httpResponse = httpClient.execute(httpGet);

            reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "utf-8"));
            String inputLine;

            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }

        } catch (Exception var) {
            var.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (httpResponse != null) {
                httpResponse.close();
            }
            httpClient.close();
        }
        return response.toString();
    }

    /**
     * asms公用post请求
     *
     * @param url           请求地址
     * @param postingString 请求data串
     * @return
     * @throws IOException
     */
    public static String commonAsmsPost(String url, String postingString, String cookie) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        String res = "";
        try {

            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();// 锟斤拷锟斤拷锟斤拷锟斤拷痛锟斤拷涑笔憋拷锟�??
            httpPost.setConfig(requestConfig);

            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Accept-Encoding", "gzip, deflate");
            httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpPost.addHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
            httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpPost.addHeader("Cookie", cookie);
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.addHeader("Origin", "http://47.107.92.22:8150");
            httpPost.addHeader("Connection", "application/json;charset=UTF-8");
            httpPost.addHeader("keep-alive", "47.107.92.22:8150");

            StringEntity stringEntity = new StringEntity(postingString, Charset.forName("UTF-8"));
            httpPost.setEntity(stringEntity);
            httpResponse = httpClient.execute(httpPost);

            logger.info(httpResponse.toString());


            res = EntityUtils.toString(httpResponse.getEntity());

//            reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "utf-8"));
//            String inputLine;
//
//            while ((inputLine = reader.readLine()) != null) {
//                response.append(inputLine);
//            }

        } catch (Exception var) {
            var.printStackTrace();
        } finally {
//            if (reader != null) {
//                reader.close();
//            }
            if (httpResponse != null) {
                httpResponse.close();
            }
            httpClient.close();
        }
        return res;
    }

    public static String commonAsmsGet(String url, String cookie) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {

            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();// 锟斤拷锟斤拷锟斤拷锟斤拷痛锟斤拷涑笔憋拷锟�??
            httpGet.setConfig(requestConfig);

            httpGet.addHeader("Accept",
                    "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
            httpGet.addHeader("Accept-Encoding", "gzip, deflate");
            httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpGet.addHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
            httpGet.addHeader("Cookie", cookie);
            httpGet.addHeader("Connection", "keep-alive");
            httpGet.addHeader("Host", "47.107.92.22:8150");

            httpResponse = httpClient.execute(httpGet);

            reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "utf-8"));
            String inputLine;

            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }

        } catch (Exception var) {
            var.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (httpResponse != null) {
                httpResponse.close();
            }
            httpClient.close();
        }
        return response.toString();
    }
}
